package com.gzhryc.servlet.velocity;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.config.I18nTools;
import com.gzhryc.servlet.AbsVelocityTools;
import com.gzhryc.servlet.WebUtils;

import java.util.Properties;

public class VelocityI18nTools extends AbsVelocityTools {

	public final static String Alias = "i18n";

	I18nTools.I18n i18n;
	String defLang = "en";

	@Override
	public String getAlias() {
		return Alias;
	}

	public String get(String... names) {
		String result = "";
		if (this.i18n != null && names != null) {
			for (int i = 0; i < names.length; i++) {
				result = result + this.i18n.get(names[i]);
			}
		}
		return result;
	}

	public String getBySpace(String space, String... names) {
		String result = "";
		if (this.i18n != null && names != null) {
			for (int i = 0; i < names.length; i++) {
				result = result + space + this.i18n.get(names[i]);
			}
		}
		if (result.length() > space.length()) {
			result = result.substring(space.length());
		}
		return result;
	}

	public String getOrDef(String name, String defValue) {
		if(this.i18n != null && StringUtils.isNotBlank(name)) {
			return this.i18n.get(name, defValue);
		}
		return defValue;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
		String lang = WebUtils.getString(request, "lang", request.getLocale().getLanguage());
		if (StringUtils.isNotBlank(lang)) {
			I18nTools.setCurrentLang(lang);
		}
		this.i18n = I18nTools.getCurrentI18n();
		if (this.i18n == null) {
			I18nTools.setCurrentLang(defLang);
			this.i18n = I18nTools.getCurrentI18n();
			if (this.i18n == null) {
				this.i18n = new I18nTools.I18n(new Properties());
			}
		}
	}

}
